package com.fowo.api.sys.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.model.RException;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.entity.SysPost;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.mapper.SysPostMapper;
import com.fowo.api.sys.mapper.SysUserPostMapper;
import com.fowo.api.sys.model.SysPostSearchParamPo;
import com.fowo.api.sys.service.SysPostService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SysPostServiceImpl extends ServiceImpl<SysPostMapper, SysPost> implements SysPostService {

    @Resource
    private SysUserPostMapper sysUserPostMapper;

    @DataActivity(action = SysDataActivityAction.Add)
    @Override
    public Long create(SysPost sysPost) {
        sysPost.doCreate();
        if (save(sysPost)) {
            return sysPost.getId();
        }
        return null;
    }

    @DataActivity(action = SysDataActivityAction.Modified)
    @Override
    public boolean update(SysPost sysPost) {
        sysPost.doUpdate();
        return updateById(sysPost);
    }
    
    @DataActivity(action = SysDataActivityAction.Del)
    @Override
    public boolean delete(Long id) {
        Integer count = sysUserPostMapper.countUserByPostId(id);
        if (count != null && count > 0) {
            throw new RException(String.format("%d 个用户包括此职位，不能删除！", count));
        }
        return removeById(id);
    }

    @Override
    public Page<SysPost> pageSearch(SysPostSearchParamPo search) {
        return baseMapper.pageSearch(search.toPage(), search);
    }

    
    @DataActivity(action = SysDataActivityAction.View)
    @Override
    public SysPost getById(Long id) {
        return super.getById(id);
    }

    @Override
    public List<SysPost> search(SysPostSearchParamPo search) {
        return baseMapper.search(search);
    }

    @Override
    public Long getIdByName(String name) {
        return baseMapper.getIdByName(name);
    }
}
